package org.example.service.impl;

import org.example.model.Student;
import org.example.model.Teacher;
import org.example.model.User;
import org.example.repository.StudentRepository;
import org.example.repository.UserRepository;
import org.example.service.StudentService;
import org.example.service.TeacherService;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2021/9/13 15:15
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser(User user) {
        userRepository.save(user);
    }


//    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addBatchUserAndStu(List<User> userList){
        for (User user:userList) {
//            try {
//                Student student = new Student(user.getName(),user.getAge());
//                addStu(student);
//            }catch (Exception e){
//                e.printStackTrace();
//            }
            addUser(user);

            Student student = new Student(user.getName(),user.getAge());
            addStu(student);



//            userRepository.save(user);
        }
    }

    private void addStu(Student student){
        studentRepository.save(student);

        Teacher teacher = new Teacher(student.getName(),student.getAge());
        teacherService.addTeacher(teacher);
    }
}
